package com.linghui.videoplus.ipai.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;

import org.apache.http.util.EncodingUtils;

import android.content.Context;

public class FileUtils {

	public static String getPreName(String url) {
		String pre = null;
		if (url != null) {
			url = url.substring(url.lastIndexOf("/") + 1);
			pre = url.substring(0, url.indexOf("."));
		}
		return pre;
	}

	/**
	 * 获取指定扩展名文件列表
	 * 
	 * @param path
	 *            文件目录
	 * @param type
	 *            扩展
	 */
	public static String[] FileFilter(String path, String type, boolean flag) {
		File file = new File(path);
		String names[] = null;
		try {
			names = file.list(filter(type, flag));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return names;
	}

	/**
	 * 文件过滤器
	 * 
	 * @param type
	 * @return
	 * @throws Exception
	 *             lock 过滤的后缀名 flag true包含、false 不包含
	 * 
	 */
	public static FilenameFilter filter(final String type, final boolean flag)
			throws Exception {
		return new FilenameFilter() {
			public boolean accept(File dir, String path) {
				String filename = new File(path).getName();
				if (flag) {
					return filename.indexOf(type) != -1;
				} else {
					return filename.indexOf(type) == -1;
				}
			}
		};
	}

	/**
	 * 读文件
	 * 
	 * @param fileName
	 * @return
	 */
	public static String readFileData(String fileName) {
		String strContent = null;
		try {
			FileInputStream fin = new FileInputStream(fileName);
			int length = fin.available();
			byte[] buffer = new byte[length];
			fin.read(buffer);
			strContent = EncodingUtils.getString(buffer, "UTF-8");
			fin.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strContent;

	}

	/**
	 * 写文件
	 * 
	 * @param fileName
	 * @param message
	 * @param mContent
	 */
	public static void writeFileData(String fileName, String message,
			Context mContent) {
		try {
			File f = new File(fileName);
			if (!f.exists()) {
				f.createNewFile();
			}
			FileOutputStream fout = new FileOutputStream(fileName);
			byte[] bytes = message.getBytes();
			fout.write(bytes);
			fout.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取文件大小
	 * @param fileName
	 * @return
	 */
	public static int getFileSize(String fileName) {
		int length = 0;
		File file = null;
		FileInputStream fis = null;
		try {
			file = new File(fileName);
			fis = new FileInputStream(file);
			length = fis.available();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return length;
	}
}
